import pandas as pd
from textblob import Word
import nltk
from lemminflect import getInflection, getLemma
import os
from pathlib import Path

# 本地NLTK数据路径配置（需手动确认路径）
nltk_data_path = Path('D:\\dev\\git\\gitee\\dict\\nltk_data')  # 请替换为实际路径

# 验证NLTK数据完整性
required_files = {
    'corpora/wordnet',
    'corpora/omw-1.4',
    'taggers/averaged_perceptron_tagger'
}

# 检查文件是否存在
missing_files = []

for f in required_files:
    if not (Path(nltk_data_path / f)).exists():
        missing_files.append(f)

if missing_files:
    raise FileNotFoundError(f"缺少必要NLTK文件: {', '.join(missing_files)}")

# 配置NLTK环境
nltk.data.path = [str(nltk_data_path)]
os.environ['NLTK_DATA'] = str(nltk_data_path)


def get_verb_forms(word):
    """本地数据动词变形处理"""
    try:
        lemma = getLemma(word, upos='VERB')[0]
        return (
            getInflection(lemma, tag='VBD')[0] or '',
            getInflection(lemma, tag='VBN')[0] or '',
            getInflection(lemma, tag='VBG')[0] or ''
        )
    except Exception:
        return ('', '', '')


def enhanced_pos_tag(word):
    """增强型本地词性标注"""
    try:
        return nltk.pos_tag([word])[0][1]
    except LookupError:
        return Word(word).tags[0][1] if Word(word).tags else ''


def get_word_forms(word):
    word = str(word).strip().lower()
    forms = {
        'lemma': word,
        'plural': '',
        'present_3rd': '',
        'present_participle': '',
        'past_tense': '',
        'past_participle': '',
        'comparative': '',
        'superlative': '',
        'passive_voice': ''
    }

    try:
        pos = enhanced_pos_tag(word)

        # 名词处理
        if pos.startswith('NN'):
            plural = Word(word).pluralize()
            forms['plural'] = plural if plural != word else ''

        # 动词处理
        if pos.startswith('VB'):
            past, past_p, pres_p = get_verb_forms(word)
            forms.update({
                'past_tense': past,
                'past_participle': past_p,
                'present_participle': pres_p,
                'present_3rd': getInflection(word, tag='VBZ')[0] if pos == 'VB' else '',
                'passive_voice': f"be {past_p}" if past_p else ''
            })

        # 形容词处理
        if pos.startswith('JJ'):
            forms['comparative'] = Word(word).comparative()
            forms['superlative'] = Word(word).superlative()

    except Exception as e:
        print(f"处理警告：{word} - {type(e).__name__}")

    return forms


def process_words(input_file, output_file):
    """本地数据处理流程"""
    df = pd.read_excel(input_file)
    df['headword'] = df['headword'].astype(str).str.strip().str.lower()
    words = df['headword'].unique().tolist()  # 去重

    results = []
    for i, word in enumerate(words, 1):
        try:
            results.append(get_word_forms(word))
            if i % 500 == 0:
                print(f"处理进度：{i}/{len(words)}")
        except Exception as e:
            print(f"严重错误：{word} - {type(e).__name__}")
            results.append({'lemma': word})

    pd.DataFrame(results).to_excel(output_file, index=False)
    print(f"处理完成，文件已保存至：{output_file}")


# 使用示例
process_words("../data/known_words.xlsx", "word_forms.xlsx")